#include "sqlitewriter.h"
#include "global.h"
#include "publicstruct.h"

SqliteWriter::SqliteWriter(QObject *parent)
    : QObject{parent}
{
    m_stopThread = false;
    m_taskFinishFlag = false;
    m_currentDealNum =0;
    m_db = QSqlDatabase::addDatabase("QSQLITE");
    m_db.setDatabaseName("./dn.db");
    if (!m_db.open()) {
        qDebug() << "Failed to open database";
    }
    else
        qDebug() << "success  to open database";
}

SqliteWriter::~SqliteWriter()
{
    qDebug()<<__FUNCTION__<<"我要退出SqliteWriter线程，释放db";
    m_db.close();
}

void SqliteWriter::run()
{
    qDebug()<<__FUNCTION__<<"开始 SqliteWriter线程的run";
    GlobalQueue* queue = GlobalQueueSingleton::instance();
    while (true) {
        if(m_stopThread)
        {
            qDebug()<<"退出SqliteWriterrun,清除队列";
            //queue->clearQueue();
            break;
        }
        //qDebug()<<"获取SQL队列长度:"<<queue->getQueueLen()<<"已处理:"<<m_currentDealNum;
        DomainInfo item = queue->dequeue();
        //qDebug()<<item.Id<<queue->getQueueLen()<<"2";
        if(item.Id==-1)
        {
            //qDebug()<<"sqlWrite队列长度为空,开始休眠300毫秒"<<m_currentDealNum;
            QThread::msleep(300);
            if(m_taskFinishFlag)
            {
                qDebug()<<"loadDomainQueryTask已正常退出,SqliteWriterTask应该正常退出";
                break;
            }
        }
        else
        {
            g_updateDomainDetailInfoByIdToSqlite(item,m_db);
            emit progressChanged(++m_currentDealNum);
        }
    }
    qDebug()<<"已完成SqliteWriter入库的数量："<<m_currentDealNum;
    delete this;
}

void SqliteWriter::abnormalStopThread()
{
    m_stopThread = true;
    qDebug()<<__FUNCTION__<<"接收到提前终止abnormalStopThread的信号，准备退出SqliteWriter线程";
    emit finishedTask();
}

void SqliteWriter::normalStopThread()
{
    m_taskFinishFlag = true;
    qDebug()<<__FUNCTION__<<"接收到normalStopThread的信号，准备退出SqliteWriter线程";

}
